import cv2 as cv
print(cv.__file__) # 打印出来的目录里面的 data目录下，就是训练好的检测器，包括面部，眼睛，猫脸等等
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei' #中文显示
cap=cv.VideoCapture(0)


while(True):
    ret ,frame = cap.read()
    if ret == True:
        ret, img = cap.read()
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        # 2.实例化OpenCV人脸和眼睛识别的分类器
        face_cas = cv.CascadeClassifier("../venv/lib/site-packages/cv2/data/haarcascade_frontalface_default.xml")
        face_cas.load('../venv/lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')
        eyes_cas = cv.CascadeClassifier("../venv/lib/site-packages/cv2/data/haarcascade_eye.xml")
        eyes_cas.load("../venv/lib/site-packages/cv2/data/haarcascade_eye.xml")
        # 3.调用识别人脸
        faceRects = face_cas.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))
        for faceRect in faceRects:
            x, y, w, h = faceRect
            # 框出人脸
            cv.rectangle(frame, (x, y), (x + h, y + w), (0, 255, 0), 3)
            # 4.在识别出的人脸中进行眼睛的检测
            roi_color = img[y:y + h, x:x + w]
            roi_gray = gray[y:y + h, x:x + w]
            eyes = eyes_cas.detectMultiScale(roi_gray)
            #画眼睛
            for (ex, ey, ew, eh) in eyes:
                cv.rectangle(frame, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)
            # frame=cv.resize(frame,(600,800))
            frame=frame[0:900, 150:600] #调整摄像头的尺寸宽窄
            cv.imshow('frame', frame)
        if cv.waitKey(25) & 0xFF == ord('q'):
            break
    else:
        break

# 5. 资源释放
cap.release()
cv.destroyAllWindows()